package org.xvergabe.forms.poc.pdfgenerator;

import org.xvergabe.forms.poc.events.PdfFieldBoolCellEvent;
import org.xvergabe.forms.poc.events.PdfFieldStringCellEvent;
import org.xvergabe.forms.poc.helper.Labeller;
import org.xvergabe.xsd.forms.components.x20.Boolean;
import org.xvergabe.xsd.forms.components.x20.ProvidedDocuments;
import org.xvergabe.xsd.forms.components.x20.String;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Class to write a ProvidedDocuments Component to a PDF
 * 
 * @author schiller
 *
 */
public class ProvidedDocumentsPdfWriter implements XmlPdfWriter<ProvidedDocuments> {

	@Override
	public void writePdfFromXml(ProvidedDocuments providedDocuments, PdfWriter writer, Document document) {

		CheckGroupPdfWriter checkGroupPdfWriter = new CheckGroupPdfWriter();
		String[] documents = providedDocuments.getDocumentArray();
		PdfPCell cell;
		PdfPTable table;
		int[] widths = { 1, 10, 10 };
		int colspan; 

		try {

			document.add(Labeller.getLabelParagraphFor(providedDocuments));

			//given documents to choose
			if (providedDocuments.getGivenDocuments() != null) {
				checkGroupPdfWriter.writePdfFromXml(providedDocuments.getGivenDocuments(), writer, document);
			}

			//additional documents
			for (int i = 0; i < documents.length; i++) {
				
				table = new PdfPTable(3);
				table.setWidths(widths);
				
				// Checkbox
				cell = new PdfPCell();
				Boolean checkboxBoolean = Boolean.Factory.newInstance();
				checkboxBoolean.setId(documents[i].getId()+".checkboxBoolean"+i);
				cell.setCellEvent(new PdfFieldBoolCellEvent(checkboxBoolean));
				
				table.addCell(cell);

				// Label. if not set it'll be created a 2 column input field 
				if (documents[i].getLabelled()) {
					cell = new PdfPCell(Labeller.getLabelParagraphFor(documents[i]));
					cell.setBorder(PdfPCell.NO_BORDER);
					table.addCell(cell);
					colspan = 1;
				} else {
					colspan = 0;
				}

				// zusätzliche Eingabe
				cell = new PdfPCell();
				cell.setBorder(PdfPCell.BOTTOM);
				cell.setColspan(2 - colspan);
				cell.setMinimumHeight(20);
				cell.setCellEvent(new PdfFieldStringCellEvent(documents[i]));
				table.addCell(cell);

				// Spaceline
				cell = new PdfPCell();
				cell.setBorder(PdfPCell.NO_BORDER);
				cell.setColspan(3);
				cell.setMinimumHeight(5);
				table.addCell(cell);
				
				document.add(table);
				
			}

		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

}
